package device

import (
    "SmartSearch/internal/models"
    "SmartSearch/internal/repositories"
    "SmartSearch/internal/responses"
    "github.com/gin-gonic/gin"
    "net/http"
    "strconv"
)

type Controller struct {
    deviceRepository *repositories.DeviceRepository
}

func NewDeviceController() *Controller {
    return &Controller{
        deviceRepository: &repositories.DeviceRepository{},
    }
}

func (d *Controller) Add(c *gin.Context) {
    var params struct {
        UserId  *int64 `json:"userId,omitempty"`
        Sn      string `json:"sn"`
        Imei    string `json:"imei,omitempty"`
        Brand   string `json:"brand,omitempty"`
        Model   string `json:"model,omitempty"`
        Version string `json:"version,omitempty"`
        Enabled bool   `json:"enabled,omitempty"`
    }
    if err := c.BindJSON(&params); err != nil {
        c.JSON(http.StatusOK, responses.GenFailResult("参数解析错误"))
        return
    }
    if d.deviceRepository.FindBySn(params.Sn) != nil {
        c.JSON(http.StatusOK, responses.GenFailResult("设备SN已存在"))
        return
    }
    device := &models.Device{
        UserId:  params.UserId,
        Sn:      params.Sn,
        Imei:    params.Imei,
        Brand:   params.Brand,
        Model:   params.Model,
        Version: params.Version,
        Enabled: params.Enabled,
    }
    if err := d.deviceRepository.Add(device); err != nil {
        c.JSON(http.StatusOK, responses.GenFailResult("设备添加失败"))
        return
    }
    c.JSON(http.StatusOK, responses.GenSuccessResult(nil))
}

func (d *Controller) Del(c *gin.Context) {
    var body struct {
        Id int64 `json:"id"`
    }
    if err := c.BindJSON(&body); err != nil {
        c.JSON(http.StatusOK, responses.GenFailResult("参数解析错误"))
        return
    }
    if _, err := d.deviceRepository.FindById(body.Id); err != nil {
        c.JSON(http.StatusOK, responses.GenFailResult("设备不存在"))
        return
    }
    if err := d.deviceRepository.Del(body.Id); err != nil {
        c.JSON(http.StatusOK, responses.GenFailResult("设备删除失败"))
        return
    }
    c.JSON(http.StatusOK, responses.GenSuccessResult(nil))
}

func (d *Controller) List(c *gin.Context) {
    name := c.Query("name")
    var enable *bool
    if s, err := strconv.ParseBool(c.Query("enable")); err == nil {
        enable = &s
    }
    current, _ := strconv.ParseInt(c.DefaultQuery("current", "0"), 10, 32)
    pageSize, _ := strconv.ParseInt(c.DefaultQuery("pageSize", "10"), 10, 32)
    list := d.deviceRepository.GetList(name, enable, int32(current), int32(pageSize))
    c.JSON(http.StatusOK, responses.GenSuccessResult(list))
}
